import React from 'react';
import './OCRTable.css';

const OCRTable = ({ ocrData }) => {
    // 解析标题-表格组（保持原有逻辑）
    const parseTableGroups = () => {
        const groups = [];
        const pages = ocrData?.result?.pages || [];
        let pendingTitle = null;

        pages.forEach(page => {
            const tables = page.tables || [];
            tables.forEach(table => {
                const isTitleBlock = table.table_cells.length === 0 && table.lines?.length > 0;
                const isTableBlock = table.table_cells.length > 0;

                if (isTitleBlock) {
                    pendingTitle = combineTitles(table.lines);
                } else if (isTableBlock) {
                    groups.push({ title: pendingTitle, table: table });
                    pendingTitle = null;
                }
            });
        });
        return groups;
    };

    const combineTitles = (lines) => {
        if (!lines?.length) return null;
        const validLines = lines.filter(line => line.direction === 1);
        if (validLines.length === 0) return null;
        const sortedLines = validLines.sort((a, b) => a.position[0] - b.position[0]);
        return sortedLines.map(line => line.text).join(' ');
    };

    const tableGroups = parseTableGroups();

    return (
        <div className="ocr-table-container">
            {tableGroups.map((group, index) => (
                <div key={index} className="table-group">
                    {group.title && <h3 className="table-title">{group.title}</h3>}
                    <TableRenderer table={group.table} /> {/* 渲染无表头的表格 */}
                </div>
            ))}
        </div>
    );
};

// 无表头的表格渲染组件（关键修改）
const TableRenderer = ({ table }) => {
    const { table_cells: cells = [], table_rows: rowCount = 0, table_cols: colCount = 0 } = table;
    const mergeInfo = createMergeInfo(cells);

    return (
        <table className="merged-table">
            {/* 移除<thead>，所有行均在<tbody>中渲染 */}
            <tbody>
                {/* 渲染全部行（从第0行开始） */}
                {Array.from({ length: rowCount }, (_, row) => (
                    <tr key={`row-${row}`}>
                        {Array.from({ length: colCount }, (_, col) => {
                            const key = `${row},${col}`;
                            const cell = mergeInfo.get(key);
                            if (!cell) return null;

                            return (
                                <td
                                    key={`cell-${row}-${col}`}
                                    rowSpan={cell.rowSpan}
                                    colSpan={cell.colSpan}
                                    className="table-cell"
                                    style={{ whiteSpace: 'pre-wrap' }}
                                >
                                    {cell.text}
                                </td>
                            );
                        })}
                    </tr>
                ))}
            </tbody>
        </table>
    );
};

// 合并单元格信息（保持原有逻辑）
const createMergeInfo = (cells) => {
    const mergeInfo = new Map();
    cells.forEach(cell => {
        const { start_row: row, start_col: col, end_row, end_col, text } = cell;
        const key = `${row},${col}`;
        if (mergeInfo.has(key)) return;
        
        const rowSpan = end_row - row + 1;
        const colSpan = end_col - col + 1;
        mergeInfo.set(key, { rowSpan, colSpan, text });
    });
    return mergeInfo;
};

export default OCRTable;